/*
 * @lc app=leetcode.cn id=637 lang=cpp
 *
 * [637] 二叉树的层平均值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  map<int, vector<long long>> m;

  vector<double> averageOfLevels(TreeNode* root)
  {
    m = map<int, vector<long long>>();
    vector<double> ans;
    DFS(0, root);
    for (auto& kv : m)
      ans.push_back(accumulate(kv.second.begin(), kv.second.end(), 0LL) / (double) kv.second.size());
    return ans;
  }

  void DFS(int level, TreeNode* root)
  {
    if (root) {
      m[level].push_back(root->val);
      DFS(level + 1, root->left);
      DFS(level + 1, root->right);
    }
  }
};
// @lc code=end
